package com.jwdf.uda.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentPhotoBinding;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.io.File;
import java.util.ArrayList;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by Administrator on 2016/5/17.
 */
public class PhotoActivity extends AbsTitleBarActivity {
    private final static String EXTRA_IMAGES = "mImages";
    private final static String EXTRA_INDEX = "mIndex";
    private final static String EXTRA_AVATAR = "avatar";
    private final static String EXTRA_USERINFO = "usreinfo";
    private ArrayList<String> mImages;
    private int mIndex;
    private int mAvatar=0;
    private PbBean.PbUserInfo mUserInfo;

    public static void start(Context context, ArrayList<String> images, int index) {
        Intent intent = new Intent(context, PhotoActivity.class);
        intent.putStringArrayListExtra(EXTRA_IMAGES, images);
        intent.putExtra(EXTRA_INDEX, index);
        context.startActivity(intent);
    }

    public static void start(Context context, ArrayList<String> images, int index , int avatar , PbBean.PbUserInfo userInfo) {
        Intent intent = new Intent(context, PhotoActivity.class);
        intent.putStringArrayListExtra(EXTRA_IMAGES, images);
        intent.putExtra(EXTRA_INDEX, index);
        intent.putExtra(EXTRA_AVATAR, avatar);
        intent.putExtra(EXTRA_USERINFO,userInfo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mIndex = getIntent().getIntExtra(EXTRA_INDEX, 0);
        mImages = getIntent().getStringArrayListExtra(EXTRA_IMAGES);
        mAvatar = getIntent().getIntExtra(EXTRA_AVATAR,0);
        mUserInfo=(PbBean.PbUserInfo)getIntent().getSerializableExtra(EXTRA_USERINFO);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTopTitle() {
        return (mIndex + 1) + "/" + mImages.size();
    }


    @Override
    protected void setupTitleView() {
        if(mAvatar==1){
            setOperateTitle(getString(R.string.quiz_edit));
        }else {
            setOperateTitle(getString(R.string.head_operate_save));
        }
    }

    @Override
    public void onHeadActionClick(View view) {
        if(mAvatar==1){
            EventBusUtil.post(new SaveImageEvent(SaveImageEvent.EVENT_EDIT));
        }else {
            EventBusUtil.post(new SaveImageEvent(SaveImageEvent.EVENT_SAVE));
        }
    }

    private class SaveImageEvent implements EventBusUtil.IEvent {
        public static final int EVENT_SAVE=0x1;
        public static final int EVENT_EDIT=0x2;

        private int event;

        public SaveImageEvent(int event) {
            this.event = event;
        }

        public int getEvent() {
            return event;
        }
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new PhotoFragment();
    }

    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putInt(EXTRA_INDEX, mIndex);
        args.putStringArrayList(EXTRA_IMAGES, mImages);
        args.putSerializable(EXTRA_USERINFO,mUserInfo);
        return args;
    }

    public static class PhotoFragment extends BaseFragment {
        private static final int REQ_STORAGE = 100;
        private FragmentPhotoBinding mDataBinding;
        private PhotoPagerAdapter mAdapter;
        private ArrayList<String> mImages;
        private int mIndex;
        private PbBean.PbUserInfo mUserInfo;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mDataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_photo, container, false);
            initViews();
            return mDataBinding.getRoot();
        }

        private void initViews() {
            mImages = getArguments().getStringArrayList(EXTRA_IMAGES);
            mIndex = getArguments().getInt(EXTRA_INDEX);
            mUserInfo=(PbBean.PbUserInfo)getArguments().getSerializable(EXTRA_USERINFO);

            mDataBinding.viewPager.setOffscreenPageLimit(1);
            mDataBinding.viewPager.addOnPageChangeListener(createOnPageChangeListener());
            mAdapter = new PhotoPagerAdapter();
            mDataBinding.viewPager.setAdapter(mAdapter);
            if (mImages != null) {
                mAdapter.setData(mImages);
                mDataBinding.viewPager.setCurrentItem(mIndex);
                ((AbsTitleBarActivity) getActivity()).setTopTitle((mIndex + 1) + "/" + mImages.size());
            }
        }

        @Override
        public void onStart() {
            super.onStart();
            EventBusUtil.registerEvent(this);
        }

        @Override
        public void onStop() {
            super.onStop();
            EventBusUtil.unregisterEvent(this);
        }

        public void onEvent(SaveImageEvent event) {
            switch (event.getEvent()){
                case SaveImageEvent.EVENT_SAVE:
                    String url = mAdapter.getImageUrl(mDataBinding.viewPager.getCurrentItem());
                    saveImage(url);
                    break;
                case SaveImageEvent.EVENT_EDIT:
                    IndividualActivity.start(getContext(), mUserInfo);
                    break;
            }

        }

        @PermissionRequest(REQ_STORAGE)
        private void saveImage(String url) {
            if (RuntimePermission.hasPermissions(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                downloadImage(url);
            } else {
                RuntimePermission.requestPermissions(getContext(), getString(R.string.app_name),
                        REQ_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }

        private void downloadImage(String url) {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                ToastUtils.show(getContext(), getString(R.string.toast_no_sdcard));
                return;
            }
            showProgressDialog();
            String dir = Environment.getExternalStorageDirectory() + File.separator + "Uda/Image";
            UdaUtils.downloadImage(getContext(), url, dir, new UdaUtils.ImageLoadingListener() {
                @Override
                public void onComplete(String path) {
                    closeProgressDialog();
                    ToastUtils.show(getContext(), getString(R.string.toast_image_success));
                }

                @Override
                public void onError() {
                    closeProgressDialog();
                    ToastUtils.show(getContext(), getString(R.string.toast_image_failed));
                }
            });
        }

        private ViewPager.OnPageChangeListener createOnPageChangeListener() {
            return new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    ((AbsTitleBarActivity) getActivity()).setTopTitle((mDataBinding.viewPager.getCurrentItem() + 1) + "/" + mAdapter.getCount());
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            };
        }

        private class PhotoPagerAdapter extends PagerAdapter {

            private ArrayList<String> mImages = new ArrayList<>();

            public String getImageUrl(int position) {
                if (position < mImages.size()) {
                    return mImages.get(position);
                }
                return null;
            }

            public void setData(ArrayList<String> images) {
                mImages = images;
                notifyDataSetChanged();
            }

            public ArrayList<String> getData() {
                return mImages;
            }

            public void remove(int index) {
                mImages.remove(index);
                notifyDataSetChanged();
            }

            public void clear() {
                mImages.clear();
                notifyDataSetChanged();
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public int getCount() {
                return mImages.size();
            }

            @Override
            public View instantiateItem(ViewGroup container, int position) {
//                final SubsamplingScaleImageView photoView=new SubsamplingScaleImageView(container.getContext());
                PhotoView photoView = new PhotoView(container.getContext());
//                photoView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
//                photoView.setMinScale(1.0f);
                String url = mImages.get(position);
//                Glide.with(container.getContext())
//                        .load(url).downloadOnly(new SimpleTarget<File>() {
//                    @Override
//                    public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
//                        photoView.setImage(ImageSource.uri(Uri.fromFile(resource)), new ImageViewState(1.0f, new PointF(0, 0), 0));
//                    }
//                });
                ImageLoader.getInstance().displayImage(url, photoView);
                photoView.setTag(R.id.tag_url, url);
//                photoView.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        getActivity().finish();
//                    }
//                });
                photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                    @Override
                    public void onPhotoTap(View view, float x, float y) {
                        getActivity().finish();
                    }
                });
                container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                return photoView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        }

    }
}
